import Vue, { h } from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import store from '@/store'

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
const routes = [
  {
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/goods',
    name: 'goods',
    component: () => import(/* webpackChunkName: "Goods" */ '../views/Allgoods.vue')
  },
  {
    path: '/user',
    name: 'User',
    component: () => import(/* webpackChunkName: "User" */ '../views/User.vue'),
    children:[
      {
        path: '/user/center',
        component: () => import(/* webpackChunkName: "center" */'@/components/user/center.vue')
      },
      {
        path: '/user/cart',
        component: () => import(/* webpackChunkName: "center" */'@/components/user/Goodscart.vue')
      },
    ]
  },
  {
    path: '/myOrder',
    name:'myOrder',
    component: () => import(/* webpackChunkName: "myOrder" */ '../views/MyOrder.vue')
  },
  {
    path: '/myfree',
    name:'myfree',
    component: () => import(/* webpackChunkName: "myfree" */ '../views/Myfree.vue')
  },
  {
    path:'/goodsdetail/:id',
    name:'goodsdetail',
    component: () => import(/* webpackChunkName: "myfree" */ '@/components/home/goodsdetail.vue')
  },

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/user'|| to.path === '/myOrder' || to.path === '/myfree') {
    // 当用户想要跳转到 用户/user 页面时
    // 判断用户是否登录  -- 判断token 是否存在
    let token = localStorage.getItem('x-auth-token')
    if (token) {
      // 进行token 的鉴权 然后再去判断是否可以继续跳转
      // 我们这里只判断有没有token
      next()
    } else {
      // 提示框
      store.dispatch("AsyncToast", {
        value: "请先登录",
        icon: "info",
      });
      // 打开登录框
      store.commit('changeIsShowLogin', true)
    }
    return
  }
  next()
})

export default router
